//
//  BBLibraryNodeView.m
//  xNose
//
//  Created by ben smith on 14/09/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "BBLibraryNodeView.h"
#import "BBNode.h"
#import "BBNodeViewFactory.h"
#import "BBNodeView.h"
#import "BBViewThumbnailer.h"
#import "BBImageButtonFactory.h"
#import "BBLibraryController.h"


@implementation BBLibraryNodeView

@synthesize node;
@synthesize viewImage;

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
			float buttonSize = 25;
			NSRect buttonRect = NSMakeRect(NSMinX(self.bounds) - 3, NSMaxY(self.bounds) - buttonSize + 3, buttonSize, buttonSize);
			
			
			NSButton * button = [BBImageButtonFactory closeButtonInRect:buttonRect];
			[button setTarget:self];
			[button setAction:@selector(buttonClick)];
			[button setAutoresizingMask:NSViewMaxXMargin | NSViewMinYMargin];
			[self addSubview:button];
			
		}
    return self;
}

-(void)setNode:(BBNode*)aNode
{
	[aNode retain];
	[node release];
	node = aNode;
	// now build the view image
	[self resetViewImage];
}

-(void)buttonClick
{
	[[BBLibraryController sharedLibraryController] removeNode:self.node];
}

-(void)resetFrame
{
	if (viewImage == nil) return;
	// sets the frame to a good size for our view image
	// it sets the origin to 0,0
	NSSize isize = [viewImage size];
	float ratio = 3.0/6.0;
	drawFrame = NSMakeRect(11.0, 0.0, isize.width * ratio, isize.height * ratio);
	NSRect frameRect = NSMakeRect(0.0, 0.0, isize.width * ratio + 10, isize.height * ratio + 10);
	[self setFrame:frameRect];
}

-(void)resetViewImage
{
	BBNodeView * nodeView = [BBNodeViewFactory viewForNode:node];
	if ([node isLeaf] || [node isCollection]) {
		self.viewImage = [BBViewThumbnailer createImageFromView:nodeView];		
		[self setNeedsDisplay:YES];
		return;
	}
	node.position = NSMakePoint(0, 0);
	[BBNodeViewFactory setNodePositionsInContainer:node];
	// is a container
	if ([node hasChildren]) {
		for (BBNode* kid in node.children) {
			BBNodeView * kidView = [BBNodeViewFactory viewForNode:kid];
			[nodeView addSubview:kidView];
		}
	}
	self.viewImage = [BBViewThumbnailer createImageFromView:nodeView];		
	[self setNeedsDisplay:YES];
}

- (void)drawRect:(NSRect)rect {
    // Drawing code here.
	[viewImage drawInRect:drawFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
	
	//if ([node isContainer]) return;

	[[NSColor whiteColor] set];
	NSRect round = [self bounds];
	round.origin.x += 7;
	round.origin.y += 1;
	round.size.height -= 7;
	round.size.width -= 7;
	[[NSBezierPath bezierPathWithRoundedRect:round xRadius:5 yRadius:5] stroke];

	[[NSColor colorWithDeviceWhite:0.0 alpha:0.4] set];
	[[NSBezierPath bezierPathWithRoundedRect:round xRadius:5 yRadius:5] fill];
}

@end
